package com.lxhll.personnel.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.lxhll.personnel.common.JwtUtil;
import com.lxhll.personnel.core.ResponseData;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwtToken拦截器，验证前端传来的token
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {//1.-->get/post ajax 预先发送一次option请求，判断是否跨域	试探
            if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
                System.out.println("OPTIONS请求，放行");
                return true;
            }
            //2.验证通过
            String token = request.getHeader("authorization");  //获取前端请求头的token
            System.out.println("token:"+token);
            Integer eid = JwtUtil.verify(token);       //验证token
            if (eid != null) {
                request.setAttribute("currentId", eid);
                return true;
            }
        } catch (Exception e) {
            //异常写到前台
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().print(JSONObject.toJSONString(ResponseData.error(403,"登录失效，请重新登录",null)));
        }
        return false;
    }
}
